package jude.java.money.provide;

import java.util.List;

public abstract class BaseProvider<T> implements Provider<T> {
	public static final int EMPTY = -1;
	public static final int EOF = -2;
	
	protected int recordCount;
	protected List<T> records;
	/**
	 * 下一条记录的位置
	 */
	protected int recordIndex;
	
	protected int provide;
	/**
	 * 循环运行
	 * */
	protected boolean recycle;
	protected boolean stopped;
	
	protected abstract List<T> loadRecords();

	@Override
	public synchronized T get() {
		if (stopped || recordIndex == EMPTY || recordIndex == EOF)
			return null;
		if (records == null) {
			records = loadRecords();
			if (records == null || records.isEmpty()) {
				recordIndex = EMPTY;
				return null;
			}
			recordCount = records.size();
		}
		int i = recordIndex;
		recordIndex ++;
		if (recordIndex == records.size()) {
			recordIndex = recycle ? 0 : EOF;
		}
		provide ++;
		return records.get(i);
	}
	
	@Override
	public boolean eof() {
		return recordIndex == EMPTY || recordIndex == EOF;
	}
	
	@Override
	public String getStatus() {
		return "xxxxx: " + provide;
	}
	
	public void reset() {
		recordIndex = 0;
		records = null;
		provide = 0;
	}
	
	public void setStopped(boolean stop) {
		this.stopped = stop;
	}

	public void setRecycle(boolean recycle) {
		this.recycle = recycle;
	}
	public int getProvide() {
		return provide;
	}
}
